import { legacy_createStore, applyMiddleware } from "redux"
import logger from "redux-logger"
import thunk from "redux-thunk";
import { ALLSTATION, ALLSTATE, GETBUY, GETHISTORY, CHANGENUM, CHECKALL, GETLIST, CHECKONE, GETINDEX, ADDSHOPCAR } from "../types/store.d"
const initialState = {
  listArr: [],
  rightArr: [],
  shopArr: [],
  historyArr: [],
  buyArr: [],
  checkstate: false,
  allmoney: 0,
}

const reducer = (state: ALLSTATE = initialState, { type, payload }: ALLSTATION) => {

  //  总价
  const sumall = () => {
    let nums = 0;
    let newarr = state.shopArr;
    newarr.forEach((item, index) => {
      if (item.flag) {
        nums += item.num * item.price;
      }
    })
    state.allmoney = nums;
  }

  switch (type) {

    case GETLIST:
      let arr = [...state.listArr];
      arr = payload;
      state.listArr = arr
      state.rightArr = arr[0].content as any[];
      return { ...state }
    case GETHISTORY:
      let arrs = [...state.historyArr];
      arrs = payload;
      state.historyArr = arrs
      return { ...state }
    case GETBUY:
      let arrn = [...state.buyArr];
      arrn = payload;
      state.buyArr = arrn
      return { ...state }
    case GETINDEX:
      let arr1 = [...state.listArr];
      let arr2 = [];
      arr2 = arr1[payload].content as any[]
      state.rightArr = arr2;
      return { ...state }
    case ADDSHOPCAR:
      let arr3 = [...state.shopArr];
      let isTrue = arr3.some((item, index) => {
        return item.id === payload.id
      })
      if (isTrue) {
        arr3.forEach((item, index) => {
          if (item.id === payload.id) {
            item.num++
          }
        })
      } else {
        arr3.push(payload)
      }

      state.shopArr = arr3;
      return { ...state }
    case CHECKONE:
      let arr4 = [...state.shopArr];
      arr4.forEach((item, index) => {
        if (item.id === payload) {
          item.flag = !item.flag;
        }
      })
      state.checkstate = arr4.every(item => item.flag)
      state.shopArr = arr4;
      sumall()
      return { ...state }
    case CHECKALL:
      let arr5 = [...state.shopArr];
      let states = payload
      arr5.forEach((item, index) => {
        item.flag = states
      })
      state.shopArr = arr5;
      state.checkstate = states
      sumall()
      return { ...state }

    case CHANGENUM:
      let arr6 = [...state.shopArr];
      arr6.forEach((item, index) => {
        if (item.id == payload.id) {
          if (payload.isAdd) {
            item.num++
          } else {
            // 当商品数量大于1时，可增加和减少数量
            if (item.num > 1) {
              item.num--;
            } else {
              return
            }

          }
        }
      })
      state.shopArr = arr6;
      sumall()
      return { ...state }
    default:
      return state
  }
}
const store = legacy_createStore(reducer, applyMiddleware(logger, thunk))
export default store;